package com.example.enginetestandroid.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.enginetestandroid.MainActivity;
import com.example.enginetestandroid.R;
import com.example.enginetestandroid.interfac.OnClickTabListener;
import com.example.enginetestandroid.manager.AppFlutterEngineManager;


import io.flutter.embedding.android.FlutterFragment;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;

public class HomeFragment extends Fragment implements OnClickTabListener {

    // 1. FlutterEngine对象
    private FlutterEngine engine;
    private MethodChannel methodChannel;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View homeView = inflater.inflate(R.layout.fragment_home, container, false);
        initWithHomeFragment(homeView);
        return homeView;
    }

    /**
     * Fragment 初始化
     */
    private void initWithHomeFragment(final View hpView) {
        String engineId = String.valueOf(R.id.home_fl);
        // 2. 通过FBFlutterEngineManager获取FlutterEngine对象
        engine = AppFlutterEngineManager.flutterEngine(requireContext(), engineId, "main");
        // 3. 用FlutterEngine对象构建出一个FlutterFragment
        FlutterFragment flutterFragment = FlutterFragment.withCachedEngine(engineId).build();
        // 4. 显示FlutterFragment
        getParentFragmentManager().beginTransaction().replace(R.id.home_fl, flutterFragment).commit();

        methodChannel = new MethodChannel(engine.getDartExecutor().getBinaryMessenger(),"tab_switch");

        methodChannel.setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
                if (call.method.equals("showTab")) {
                    MainActivity activity = (MainActivity) getActivity();
                    activity.switchBottomView(true);
                } else if (call.method.equals("hideTab")) {
                    MainActivity activity = (MainActivity) getActivity();
                    activity.switchBottomView(false);
                } else {
                    result.notImplemented();
                }
            }
        });
    }

    /**
     * 跳转到 Flutter 页面
     */
    private void gotoFlutter() {
    }

    @Override
    public void onclick(int position) {

    }
}
